package com.xhwl.centiotdata.service.integrateconfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.talkback.TalkBackIntegrationConfigDTO;
import com.xhwl.common.enums.CategoryEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/31 18:47
 */
@Component
@Slf4j
public class TalkBackIntegrationConfig extends IntegrationConfig<Object, List<TalkBackIntegrationConfigDTO>> {

    private List<TalkBackIntegrationConfigDTO> talkBackIntegrationConfigMap = new ArrayList<>();

    @Override
    public List<TalkBackIntegrationConfigDTO> getIntegrationConfig(Object o) {
        return talkBackIntegrationConfigMap;
    }

    /**
     * 配置变更时，重新赋值map
     * @param event
     */
    @EventListener
    public void listenIntegrationConfig(IntegrationConfigEvent event) {
        this.handleTalkBackIntegrationConfig();
    }

    private void handleTalkBackIntegrationConfig() {
        talkBackIntegrationConfigMap = IntegrationConfig.integrationConfigList.stream()
                .filter(deviceProjSupplierCategory ->
                        // 云对讲系统
                        CategoryEnum.TALK_BACK_SYSTEM.getId().equals(deviceProjSupplierCategory.getProdCategoryId()) &&
                                deviceProjSupplierCategory.getProperties() != null)
                .map(deviceProjSupplierCategory -> {
                    JSONObject properties = deviceProjSupplierCategory.getProperties();
                    TalkBackIntegrationConfigDTO configDTO = JSON.toJavaObject(properties, TalkBackIntegrationConfigDTO.class);
                    BeanUtils.copyProperties(deviceProjSupplierCategory, configDTO);
                    if (!ObjectUtils.isEmpty(configDTO)) {
                        return configDTO;
                    } else {
                        return null;
                    }
                })
                .collect(Collectors.toList());
    }

}
